{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 载入库\n",
    "from skimage.io import imread\n",
    "from skimage.transform import resize\n",
    "import os\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 路径下图片读取，给与标签\n",
    "def load_images(path,reshape=224):\n",
    "    contents = os.listdir(path)\n",
    "    classes = [each for each in contents if os.path.isdir(os.path.join(path,each))]\n",
    "    print('目录下有%s' % classes)\n",
    "    \n",
    "    # 用labels来存储图片的类别\n",
    "    labels = []\n",
    "    # images数组用来存储图片数据\n",
    "    images = []\n",
    "    i = 0\n",
    "    # 对每个不同种类读取图片到list并且+标签\n",
    "    for i,each in enumerate(classes,0):\n",
    "        class_path = os.path.join(path,each)\n",
    "        files = os.listdir(class_path)\n",
    "        print(\"Starting {} images\".format(each),'数量为',len(files))\n",
    "        for file in files:\n",
    "            # 载入图片并放入batch数组中\n",
    "            img = imread(os.path.join(class_path, file))\n",
    "            img = img / 255.0\n",
    "            # 这里输入的是图片的缩放尺寸\n",
    "            img = resize(img, (reshape, reshape))\n",
    "            images.append(img.reshape((reshape,reshape,3)))\n",
    "            labels.append(i)   \n",
    "            \n",
    "    images = np.array(images)\n",
    "    labels = np.array(labels)\n",
    "    print('总共读取了%d张图片'%images.shape[0])\n",
    "    return images,labels # 返回图片以及对应的标签"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "目录下有['cat', 'dog']\n",
      "Starting cat images 数量为 10\n",
      "Starting dog images 数量为 10\n",
      "总共读取了20张图片\n"
     ]
    }
   ],
   "source": [
    "path='./pics/'\n",
    "train_x,train_y = load_images(path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 以.npy格式存储在当前目录下\n",
    "np.save(\"train_x.npy\",train_x) \n",
    "np.save(\"train_y.npy\",train_y)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
